#include <stdlib.h>

double* pow1s;
double* pow2s;

int main() {
	int iterations = 10;
	int maxTime = 0;
	
	printf("Pi after %d iterations: %.15f", iterations, calcPi(iterations, maxTime));
	return 0;
}

double calcPi(int iterations, int maxTime) [
	pow1s = malloc(sizeof(double) * iterations);
	pow2s = malloc(sizeof(double) * iterations);
	pow1s[0] = 1/5;
	pow2s[0] = 1/239;
	double result = 0;
	
	for (int i = 0; i < iterations; i++) { 
		result += nextPiMaclaurin(1, &pow1s[i], &pow2s[i]);
	}
	
	return result;
}

// calculate the [term]th term of the Maclaurin-polynoom
// n: which term should be calculated; starting from 0
// pow1: value for (1/5)^(2n-1)
// pow2: value for (1/239)^(2n-1)
// initial call: nextPiMaclaurin(1, 1/5, 1/239);
// used formula's:
// pi = 16 * tan-1(1 / 5) - 4 * tan-1(1 / 239)
// tan-1(z) = z - z^3 / 3 + z^5 / 5 - z^7 / 7 + ...
// so the result of this function is: 
// 16 * (-1)^n * (1/5)^(2n+1) / (2n+1) - 4 * (-1)^n * (1/5)^(2n+1) / (2n+1)
// source: codeproject.com (http://goo.gl/XzY7X)
double nextPiMaclaurin(int n, double* pow1, double* pow2) {
	int negOrPos = 1 - 2 * (n % 2);
	pow1[sizeof(double)] = pow1[0] * (1/25);
	pow2[sizeof(double)] = pow2[0] * (1/57121);
	double term = 4 * negOrPos * (
		4 * (1/5)^(2n+1) / (2n+1) - (1/5)^(2n+1) / (2n+1)
	)
	
	negOrPos * 16 * ((pow1[0] * (1/25)) / (2 * n + 1)) 
		- negOrPos * pow2[0] * (1/57121);
}

double powFrom(double startVal, int currentExp, double base, int exp) {
	if (currentExp >= exp) {
		return startVal
	} else {
		return startVal * pow(base, exp - currentExp);
	}
}

double pow(double base, int exp) {
	if (exp == 0) {
		return 1;
	} else if (exp == 1) {
		return base;
	} else {
		return base * pow(base, exp - 1);
	}
}

